package com.videoshare.admin;

import javax.servlet.http.*;

import org.apache.struts.action.*;
import org.apache.commons.logging.*;
import com.sapientia.user.dao.*;
import com.sapientia.user.UserLoginForm;
import com.sapientia.user.UserRegistrationForm;
import com.sapientia.user.UserConstants;
import java.util.*;
import java.sql.*;
import javax.sql.*;

public class UserEnableAction extends Action {

	/**
	 * @param args
	 */
	
	private static Log log = LogFactory.getLog(UserEnableAction.class);
	
	public ActionForward execute(
			ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception
	{
		
		UserRegistrationForm userForm = (UserRegistrationForm)form;
		HttpSession session = request.getSession();
        UserLoginForm loginForm = (UserLoginForm)session.getAttribute(UserConstants.USER_KEY);
		
		int page =  userForm.getPage();
		
		if(page == 0)
		{
			return processInitialPage(mapping, userForm, request, response);
		}
		else if(page == 1)
		{	
			if( (loginForm != null) && (loginForm.isLoggedIn())&& (loginForm.getProfile().equals(UserConstants.USER_ROLE_ADMINISTRATOR)))
			{
				return processPage1(mapping, userForm, request, response);
			}
			else
	        {
	        	System.out.println("User not logged in or not administrator");
	        	//throw new IllegalStateException("user not logged in");
	        	return mapping.findForward("notLoggedIn");
	        }
				
		}
		else 
		{
			//throw new IllegalStateException("page number not supported");
			return mapping.findForward("page number not supported");
					
		}
		
		
		
		
	}
	
	public ActionForward processInitialPage(ActionMapping mapping,
			UserRegistrationForm userForm,
			HttpServletRequest request,
			HttpServletResponse response
			) throws Exception
	{
		List userRegisteredList = null;
		System.out.println("inside UserEnableAction page 0");
		//int page = userForm.getPage();
		
						
		Connection conn = getDataSource(request,"userDB").getConnection();
		UserDAO dao = DAOFactory.createUserDAO(conn);
		
					
		try{
			userRegisteredList = dao.getRegisteredUsers(false);
		}		
		finally{
				conn.close();
		}
					
		
		request.setAttribute("users",userRegisteredList);
		
		return mapping.findForward("success");	
	}
	
	public ActionForward processPage1(ActionMapping mapping,
			UserRegistrationForm userForm,
			HttpServletRequest request,
			HttpServletResponse response
			) throws Exception
	{
		System.out.println("inside UserEnableAction page 1");
		
		String [] enabledUser = userForm.getSelectedUser();
		if(enabledUser != null)
		{
			System.out.println("utenti abilitati: " + enabledUser.length);
			for(int i = 0; i < enabledUser.length; i++)
				System.out.println(enabledUser[i]);
		}
		
		return mapping.findForward("success");
	}

}
